package com.springx.examples.showcase.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ImmutableMap;
import com.springx.examples.showcase.common.domain.Order;
import com.springx.examples.showcase.entity.Role;
import com.springx.examples.showcase.entity.RoleResource;
import com.springx.examples.showcase.repository.mybatis.RoleMapper;
import com.springx.examples.showcase.repository.mybatis.RoleResourceMapper;
import com.springx.examples.showcase.vo.RoleVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by roman_000 on 2015/7/15.
 */
@Service
@Transactional
public class RoleService extends BaseService<Role> {
    @Autowired
    private RoleResourceService roleResourceService;
    @Autowired
    private RoleMapper roleMapper;

    public void delete(Long[] ids) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (Long id : ids) {
                Example example = new Example(Role.class);
                example.createCriteria().andEqualTo("id", id).andEqualTo("isSystem", "1");
                List<Role> roleList = mapper.selectByExample(example);
                if (CollectionUtils.isNotEmpty(roleList)) {
                    throw new IllegalArgumentException("系统内置角色不允许删除");
                }
                mapper.deleteByPrimaryKey(id);
            }
        }
    }

    /**
     * 修改方法
     */
    public void update(Role role, List<HashMap<String, Object>> checkParams) {
        this.updateByPrimaryKeySelective(role);
        roleResourceService.insert(role.getId(), checkParams);
    }

    /**
     * 查询用户角色列表
     *
     * @return
     */
    public Page<RoleVo> findAdminRolePage(Map<String, Object> params, List<Order> orders, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<RoleVo> roleVoList = roleMapper.findAdminRoleList(params);
        PageInfo<RoleVo> pageInfo = new PageInfo<RoleVo>(roleVoList);
        Page<RoleVo> page = new PageImpl<RoleVo>(pageInfo.getList(), pageable, pageInfo.getTotal());
        return page;
    }
}
